//
//  ApplicationController.m
//  WSPluginSwitcher
//
//  @author	Jens Krause [www.websector.de]
//	@date		01/01/09
//  @see		http://www.websector.de/blog/
//
//  Licensed under the MIT License http://www.opensource.org/licenses/mit-license.php
//

#import "ApplicationController.h"
#import "PreferencesController.h"
#import "Constants.h"

@implementation ApplicationController

#pragma mark --
#pragma mark init && dealoc

+(void) initialize{

	//
	// register default values for standardUserDefaults
	NSMutableDictionary *appDefaults = [NSMutableDictionary dictionary];
	
	[appDefaults	setObject:[NSNumber numberWithBool: YES]
					forKey: KEY_CHECK_FOR_UPDATES ];	
	[appDefaults	setObject:[NSNumber numberWithBool: YES]
					forKey: KEY_RESTART_SAFARI ];	
	[appDefaults	setObject:[NSNumber numberWithBool: YES]
					forKey: KEY_RESTART_FIREFOX ];	
	
	
    [[NSUserDefaults standardUserDefaults ] registerDefaults:appDefaults];

}

-(id)init{
	if (self = [super init]) {
		// initialize appModel
		appModel = [[ApplicationModel alloc] init];
		
		[self pluginIsSwitching:NO];
	}
	return self;
}

-(void)dealloc {
	
	[prefController release];
	prefController = nil;
	
	[appModel release];
	appModel = nil;
	
	[super dealloc];
	
	
}



- (IBAction)showPreferencePanel:(id)sender {

	if (!prefController) {
		prefController = [[PreferencesController alloc] init];
		[prefController setAppModel:appModel];

	}
	
	[prefController showWindow:self];
	
			
}


- (void) awakeFromNib {	

	//
	// bind NSArrayController to ApplicationModel
	 [archiveFlashPluginsFoldersController	bind:@"content"
											 toObject: appModel 
											 withKeyPath:@"archiveFlashPluginFolders"
											 options:nil];
	
	//
	// add observers
	[archiveFlashPluginsFoldersController	addObserver:self 
											forKeyPath:@"content" 
											options:0 
											context:NULL];
	

	
	[appModel updateArchiveFlashPluginFolders];
	
	
	NSLog(@"[NSUserDefaults standardUserDefaults] %@", [[NSUserDefaults standardUserDefaults] objectForKey:KEY_RESTART_SAFARI]);
	NSLog(@"[NSUserDefaults standardUserDefaults] %@", [[NSUserDefaults standardUserDefaults] objectForKey:KEY_RESTART_FIREFOX]);
	//
	// show preference panel if an user haven't stored archive folders
	NSString *archiveFlashPluginsFolders = [[NSUserDefaults standardUserDefaults] stringForKey: KEY_ARCHIVE_FLASH_PLUGINS_FOLDERS ];
	
	if (!archiveFlashPluginsFolders){
		
		[b_switchFlashPlugin setEnabled: NO];
		[cb_flashPlugins setEnabled: NO];
		[self showPreferencePanel:nil];
	}
	
}

-(void)observeValueForKeyPath:(NSString *)keyPath 
					ofObject:(id)object 
					change:(NSDictionary *)change 
					context:(void *)context 
{
   
	if ( [keyPath isEqualToString:@"content"] ) {
        
		BOOL isSelected;
		
		//NSString *flashPluginFolderPath = [appModel selectedArchiveFolder]; 
		
		if([[archiveFlashPluginsFoldersController arrangedObjects] count] > 0) {
			isSelected = YES;
			
			[cb_flashPlugins reloadData];
			[cb_flashPlugins selectItemAtIndex:0];
			
			[self selectedArchivPluginsFolderChanged:nil];			
			
		} else {
			isSelected = NO;
		}
		
		[b_switchFlashPlugin setEnabled:isSelected];
		[cb_flashPlugins setEnabled: isSelected];

    }
	
}


-(IBAction)selectedArchivPluginsFolderChanged:(id)sender{	
	
	// NSLog(@"setSelectedArchiveFolder -> %@", [appModel selectedArchiveFlashPluginFolder]);

	[appModel setSelectedArchiveFlashPluginFolder: [appModel getValidArchiveFlashPluginFolder:
														[cb_flashPlugins objectValueOfSelectedItem]
													]];
	
	// NSLog(@"setSelectedArchiveFolder -> %@", [appModel selectedArchiveFlashPluginFolder]);
};



-(IBAction)switchFlashPluginHandler:(id)sender{
		
	[self pluginIsSwitching:YES];
	
	NSString *source1, *destination1, *source2, *destination2;
	
	source1 = [ [appModel selectedArchiveFlashPluginFolder] stringByAppendingString: FILENAME_FLASH_PLAYER_PLUGIN];
	destination1 = [ DEFAULT_PLUGINS_FOLDER stringByAppendingString: FILENAME_FLASH_PLAYER_PLUGIN];
	
	
	source2 = [ [appModel selectedArchiveFlashPluginFolder] stringByAppendingString: FILENAME_FLASH_PLAYER_XPT];
	destination2 = [DEFAULT_PLUGINS_FOLDER stringByAppendingString: FILENAME_FLASH_PLAYER_XPT];
	
	/*
	NSLog(@"source1 -> %@", source1);
	NSLog(@"destination1 -> %@", destination1);
	NSLog(@"source2 -> %@", source2);
	NSLog(@"destination2 -> %@", destination2);
	*/
	
	NSFileManager *fileManager = [NSFileManager defaultManager];

	BOOL hasPermissions;
	
	//
	// source 1 + destination 1
	hasPermissions = [self checkPermissions: source1];	
	if ([fileManager fileExistsAtPath:destination1]) 
	{
		hasPermissions = [self checkPermissions: destination1];
	}
	//
	// source 2 + destination 2	
	hasPermissions = [self checkPermissions: source2];
	if ([fileManager fileExistsAtPath:destination2]) 
	{
		hasPermissions = [self checkPermissions: destination2];
	}	
	
	
	if (!hasPermissions){
		//
		//TODO: Change permissions if possible... 
		// I don't know @ the moment how the best way could be....
		/*
		NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:source1 traverseLink:YES];
		
		NSMutableDictionary *attributes = [fileAttributes mutableCopy];
		[attributes setObject:[NSNumber numberWithUnsignedInt:0777] forKey:NSFilePosixPermissions];
		
		NSLog(@"fileAttributes NEW -> %@", attributes);
		
		BOOL success = [fileManager changeFileAttributes:attributes atPath:destination1];
		 
		 */
		
		NSAlert *alert = [NSAlert alertWithMessageText: @"Error:" 
										 defaultButton: @"Ok" 
									   alternateButton: nil 
										   otherButton:nil
							informativeTextWithFormat:[NSString stringWithFormat: @"Operation not permitted. You have to change the file permission of the installed Flash Player Plugin OR of the files located in: '%@'",
														[appModel selectedArchiveFlashPluginFolder] ]];
		
		
		[alert beginSheetModalForWindow:mainView
						modalDelegate:self 
						 didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
							contextInfo:NULL];
		
		
		[self pluginIsSwitching:NO];
		
		return;

	} 
	
	
	//
	// remove uneeded files and copy new files
	if ([fileManager removeFileAtPath: destination1 handler:nil]) 
	{
		NSLog (@"removeFileAtPath: destination1"  );
	} else{
		NSLog (@"NO removeFileAtPath: destination1"  );
	}

	if ([fileManager copyPath: source1 toPath: destination1 handler:nil]) 
	{
		NSLog (@"source1 copied");
	} else{
		NSLog (@"source1 NOT copied");
	}
	
	if ([fileManager removeFileAtPath: destination2 handler:nil]) 
	{
		NSLog (@"removeFileAtPath: destination2");
	} else{
		NSLog (@"NO removeFileAtPath: destination2");
	}

	if ([fileManager copyPath: source2 toPath: destination2 handler:nil]) 
	{
		NSLog (@"source2 copied"  );
	} else{
		NSLog (@"source2 NOT copied"  );
	}

	//
	// restart browsers??	
	NSWorkspace * ws = [NSWorkspace sharedWorkspace];
	NSArray * launchedApplications = [ws valueForKeyPath:@"launchedApplications.NSApplicationName"];
	
	BOOL firefoxIsOpened = NO;
	BOOL safariIsOpened = NO;
	//
	// check launched browsers
	NSString *app;
	for (app in launchedApplications) {
		
		if ([app isEqual: @"Safari"]) {
			safariIsOpened = YES;			
		} else if([app isEqual: @"Firefox"]){
			firefoxIsOpened = YES;	
		}		
	}	
	
	NSString *scriptTxt;
	NSString *browserName;
	NSString *url = @"http://www.playerversion.com/";
	//
	// handle restarting firefox
	if ([[NSUserDefaults standardUserDefaults] boolForKey: KEY_RESTART_FIREFOX]){	

		browserName = @"Firefox";
		
		if (firefoxIsOpened){
			
			scriptTxt =  [NSString stringWithFormat: @"\ntell application \"%@\"\n\tquit\n\tdelay 2\n activate \n\t open location \"%@\"\nend tell", 
						  browserName, url];
			[self restartBrowser: scriptTxt ];	
			
		} else {	
			scriptTxt = [NSString stringWithFormat: @"tell application \"%@\"\n\t activate \n\t open location \"%@\"\nend tell",
						 browserName, url];
			
			[self restartBrowser: scriptTxt ];
		}
	}
	//
	// handle restarting safari
	if ([[NSUserDefaults standardUserDefaults] boolForKey: KEY_RESTART_SAFARI]){		
		browserName = @"Safari";
		
		if (safariIsOpened){
			
			scriptTxt =  [NSString stringWithFormat: @"\ntell application \"%@\"\n\tquit\n\tdelay 2\n activate \n\t open location \"%@\"\nend tell", 
						  browserName, url];
			[self restartBrowser: scriptTxt ];	
			
		} else {	
			scriptTxt = [NSString stringWithFormat: @"tell application \"%@\"\n\t activate \n\t open location \"%@\"\nend tell",
												browserName, url];
			
			[self restartBrowser: scriptTxt ];
		}
	}	

	[self pluginIsSwitching:NO];
	
}

- (IBAction)restartFirefoxHandler:(id)sender{

	int state = [chb_restartFirefox state];
	[[NSUserDefaults standardUserDefaults] setBool:state 
											forKey: KEY_RESTART_FIREFOX];

}


- (IBAction)restartSafariHandler:(id)sender{


	int state = [chb_restartSafari state];
	[[NSUserDefaults standardUserDefaults] setBool:state 
											forKey: KEY_RESTART_SAFARI];	

}






-(BOOL) checkPermissions:(NSString *)filePath{

	// show permissions
	// Converting NSFilePosixPermissions to Octal representation
	// @see: http://www.mail-archive.com/cocoa-dev@lists.apple.com/msg16346.html
	// 775
	// 777
	NSFileManager *fileManager = [NSFileManager defaultManager];	
	
	NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:filePath traverseLink:YES];
	unsigned long perms = [[fileAttributes objectForKey:NSFilePosixPermissions] unsignedLongValue];
	NSString *permsInOctal = [NSString stringWithFormat:@"%o", perms]; // 511 == 777;
	
	NSLog ([NSString stringWithFormat:@"PERMISSION OF %@ is %@", filePath, permsInOctal]);
	
	BOOL hasPermissions = ([permsInOctal isEqual: @"777"]);
	
	return hasPermissions;
	

}

-(void)	alertDidEnd:(NSAlert *)alert 
					returnCode:(int)returnCode 
					contextInfo:(void *)contextInfo {
	
	NSLog(@"Alert sheet ended");
	

}

-(void) restartBrowser:(NSString *) scriptTxt {
	
	NSAppleEventDescriptor *result;
	
	// NSLog (scriptTxt);
	
	NSAppleScript *script = [[NSAppleScript alloc] initWithSource: scriptTxt];
	result = [script executeAndReturnError:nil];
	
	if ((result != nil) && ([result descriptorType] != kAENullEvent)) {
		NSLog ([NSString stringWithFormat:@"AppleScript has been finished: \"%@\"", scriptTxt]);
	}
	else
	{
	NSLog ([NSString stringWithFormat:@"result: \"%@\"", result]);
	}
	
	
	[scriptTxt release];		
	
}


-(void) pluginIsSwitching:(BOOL) value{
	
	//
	// behavior of loader image
	if (value){
		[loader startAnimation:nil];
	}
	else{
		[loader stopAnimation:nil];
	}
	
	[loader setHidden: !value];
	[b_switchFlashPlugin setEnabled:!value];

}


@end
